package com.gcsoftware.web.service.elasticsearch;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

import java.util.List;

/**
 * ES 连接
 * @author czp
 * date : 2018-04-14
 */
public class Transport {
    private static volatile Transport instance = null;
    private RestClient client;
    private HttpHost[] httpHosts;
    private int conTimeOut = 50000;    // 连接超时，默认[5000ms]
    private int socketTimeOut = 60000; // 接口超时，默认[6000ms]
    private int maxRstTimeOut = 60000; // 连接最大重试时间,默认[60000ms]
    private List<String> hosts;

    private HttpHost[] setHttpHosts() {
        if (hosts != null && hosts.size() > 0) {
            int size = hosts.size();
            httpHosts = new HttpHost[size];
            for (int i = 0; i < hosts.size(); i++) {
                String temp [] = hosts.get(i).split(":");
                HttpHost newHttpHost = new HttpHost(temp[0], Integer.valueOf(temp[1]).intValue(), "http");
                httpHosts[i] = newHttpHost;
            }
        }
        return httpHosts;
    }

    public Transport(List<String> hosts) {
        this.hosts = hosts;
        client = RestClient.builder(setHttpHosts()).setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback(){
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder builder) {
                return builder.setConnectionRequestTimeout(conTimeOut).setSocketTimeout(socketTimeOut);
            }
        }).setMaxRetryTimeoutMillis(maxRstTimeOut).build();
    }

    public static Transport getInstance(List<String> hosts) {
        if (instance == null) {
            synchronized (Transport.class) {
                if (instance == null) {
                    instance = new Transport(hosts);
                }
            }
        }
        return instance;
    }

    public RestClient getClient() {
        return client;
    }
}
